/*
 * @Description: 订单校验规则页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2020-10-21 17:30:52
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-25 16:48:09
 */

import { renderSort } from '@src/utils/utilsFun';
import { Button, DataSet, Lov, notification, Table } from 'choerodon-ui/pro/lib';
import { ButtonColor, FuncType } from 'choerodon-ui/pro/lib/button/enum';
import { SelectionMode, TableColumnTooltip } from 'choerodon-ui/pro/lib/table/enum';
import { Buttons, TableProps } from 'choerodon-ui/pro/lib/table/Table';
import React, { useCallback, useMemo, useState } from 'react';
import intl from 'utils/intl';
import { routerRedux } from 'dva/router';
import querystring from 'querystring';
import { connect } from 'dva';
import { useDataSet, useDataSetEvent } from 'hzero-front/lib/utils/hooks';
import { recommendedQuantityDateSet } from '../../../stores/orderDistributionDtlDS';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import moment from 'moment';

notification.config({
  duration: 3,
  placement: 'bottomRight',
});
interface propstype {
  dispatch: any;
  tableDS: DataSet;
  parentDS: DataSet;
}

const ClassPage: React.FC<propstype> = ({ parentDS, tableDS, dispatch }) => {
  const recommendedQuantityDS = useDataSet(
    () => new DataSet(recommendedQuantityDateSet() as DataSetProps)
  );

  const [addFalg, setAddFalg] = useState(true);

  // 新建行
  const handleCreate = () => {
    const record = tableDS.create({});
    record.set('customerType', parentDS.current?.get('customerType'));
  };

  // 订单编号加载监听事件
  const optionLoadListener = () => {
    const optionDs = tableDS.current?.getField('orderObj')?.options as DataSet;
    console.log('optionLoadListener');
    // 明细表的数据
    const selectData = tableDS.toData();
    optionDs.forEach((record: any) => {
      // 明细列表已有订单数据，不可勾选
      const odpId = record.get('odpId');
      if (selectData.some((selected: any) => selected.orderDeskProductId === odpId)) {
        record.selectable = false;
      } else {
        record.selectable = true;
      }
    });
  };
  // 删除选择行
  const handleDelete = () => {
    const seletedRecord = tableDS.selected;
    if (seletedRecord.length === 0) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get(`dji.otc.om.view.reminder.selectDeleteData`).d('请勾选删除的数据'),
      });
      return;
    }
    tableDS.delete(seletedRecord);
  };

  // 获取建议数量
  const reqRecommendedQuantity = () => {
    //封装请求数据
    const reqParamList: any = [];
    const currentQuotaMonth = parentDS.current?.get('quotaMonth');
    const month = moment(currentQuotaMonth).format('YYYY-MM');
    tableDS.forEach(record => {
      if (record.get('orderDeskProductId') && record.get('customerType')) {
        reqParamList.push({
          productCode: record.get('productBom'),
          areaId: parentDS.current?.get('areaId'),
          regionId: parentDS.current?.get('regionId'),
          quotaMonth: month,
          customerToken: record.get('customerCode'),
          customerType: record.get('customerType'),
          orderDeskProductId: record.get('orderDeskProductId'),
          orderQuantity: record.get('orderQuantity'),
        });
      }
    });
    if (!reqParamList.length) return;
    // 设置建议数量值 客户信用余额... 等字段
    recommendedQuantityDS.setQueryParameter('djiRecommendedQuantityDTOList', reqParamList);
    recommendedQuantityDS.query().then(res => {
      // const currentRecord = tableDS.current;
      // const orderDeskProductId = currentRecord?.get('orderDeskProductId');
      // res.forEach(item => {
      //   if (item.orderDeskProductId === orderDeskProductId) {
      //     currentRecord?.set('suggestedQuantity', item.recommendedQuantity);
      //     currentRecord?.set('customerCreditBalance', item.customerCreditBalance);
      //     currentRecord?.set('kaAvailableQuantityByArea', item.kaAvailableQuantityByArea);
      //     currentRecord?.set('othersAvailableQuantityByArea', item.othersAvailableQuantityByArea);
      //     currentRecord?.set('kaAvailableQuantityByRegion', item.kaAvailableQuantityByRegion);
      //     currentRecord?.set(
      //       'othersAvailableQuantityByRegion',
      //       item.othersAvailableQuantityByRegion
      //     );
      //     currentRecord?.set('currentMonthAvailableQuota', item.currentMonthAvailableQuota);
      //     currentRecord?.set('currentMonthQuota', item.currentMonthQuota);
      //   }
      // });
      if (res.msg) {
        notification.warning({
          placement: 'bottomRight',
          message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
          description: res.msg,
        });
        tableDS.reset();
        return;
      }
      tableDS.forEach(record => {
        const currentRecord = record;
        const orderDeskProductId = currentRecord?.get('orderDeskProductId');
        for (const item of res) {
          if (Number(item.orderDeskProductId) === Number(orderDeskProductId)) {
            currentRecord?.set('suggestedQuantity', item.recommendedQuantity);
            currentRecord?.set('customerCreditBalance', item.customerCreditBalance);
            currentRecord?.set('kaAvailableQuantityByArea', item.kaAvailableQuantityByArea);
            currentRecord?.set('othersAvailableQuantityByArea', item.othersAvailableQuantityByArea);
            currentRecord?.set('kaAvailableQuantityByRegion', item.kaAvailableQuantityByRegion);
            currentRecord?.set(
              'othersAvailableQuantityByRegion',
              item.othersAvailableQuantityByRegion
            );
            currentRecord?.set('currentMonthAvailableQuota', item.currentMonthAvailableQuota);
            currentRecord?.set('currentMonthQuota', item.currentMonthQuota);
            break;
          }
        }
      });
    });
  };

  useDataSetEvent(parentDS, 'update', ({ dataSet, name, value }) => {
    if (name === 'areaId' && dataSet.current.get('areaId')) {
      // 设置订单编号lov查询条件
      tableDS.forEach(record => {
        record.set('orderObj', null);
      });
      const areaId = parentDS.current?.get('areaId');
      const orderObjField = tableDS.getField('orderObj');
      orderObjField?.setLovPara('areaId', areaId);
    }

    if (name === 'quotaMonth' || name === 'areaId') {
      // 头表 选了小区、月份才能新增分货明细
      if (dataSet.current.get('quotaMonth') && dataSet.current.get('areaId')) {
        reqRecommendedQuantity();
        setAddFalg(false);
      } else {
        setAddFalg(true);
      }
    }

    // 头上客户类型改变，行的类型也要改变
    if (name === 'customerType' && dataSet.current.get('customerType')) {
      tableDS.forEach(record => {
        record.set('customerType', value);
      });
    }
  });

  // 订单编号和客户类型选了才去请求建议数量
  useDataSetEvent(tableDS, 'update', ({ dataSet, name }) => {
    if (name === 'orderObj' || name === 'customerType') {
      if (dataSet.current.get('orderObj') && dataSet.current.get('customerType')) {
        reqRecommendedQuantity();
      }
    }
  });

  useDataSetEvent(tableDS, 'load', ({ dataSet }) => {
    if (dataSet.toData().length) {
      setAddFalg(false);
    }
  });

  const Columns = useMemo<any>(
    () => [
      {
        header: intl.get(`dji.otc.om.view.field.serialNumber`).d('序号'),
        width: 50,
        lock: true,
        renderer: ({ record }) => renderSort(record, tableDS),
      },
      {
        name: 'orderObj',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        lock: true,
        editor: ({}) => (
          <Lov
            name="orderObj"
            tableProps={{ selectionMode: SelectionMode.rowbox } as TableProps}
            onClick={() => {
              const optionDs = tableDS.current?.getField('orderObj')?.options as DataSet;
              optionDs.addEventListener('load', optionLoadListener);
            }}
          />
        ),
        width: 170,
      },
      {
        name: 'customerCode',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        width: 150,
      },
      {
        name: 'customerType',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        width: 150,
        editor: true,
      },
      { name: 'productCode', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'productName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'orderQuantity', align: 'left', tooltip: TableColumnTooltip.always },
      {
        name: 'unallocatedQuantity',
        align: 'left',
        tooltip: TableColumnTooltip.always,
      },
      {
        name: 'suggestedQuantity',
        align: 'left',
        tooltip: TableColumnTooltip.always,
      },
      { name: 'quantity', editor: true, align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'reason', editor: true, align: 'left', tooltip: TableColumnTooltip.always },
      {
        name: 'customerCreditBalance',
        align: 'left',
        tooltip: TableColumnTooltip.always,
      },
      {
        name: 'kaAvailableQuantityByArea',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        width: 170,
      },
      {
        name: 'othersAvailableQuantityByArea',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        width: 150,
      },
      {
        name: 'kaAvailableQuantityByRegion',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        width: 150,
      },
      {
        name: 'othersAvailableQuantityByRegion',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        width: 150,
      },
      {
        name: 'currentMonthAvailableQuota',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        width: 170,
      },
      {
        name: 'currentMonthQuota',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        width: 170,
      },
    ],
    []
  );

  const handleBatchExport = useCallback(() => {
    dispatch(
      routerRedux.push({
        pathname: `/o2om/distribution/excel-import/O2OM_C.QUOTA_PLAN`,
        search: querystring.stringify({
          action: intl.get(`dji.otc.om.view.title.orderDistributionImport`).d('订单分货列表导入'),
          prefixPath: 'O2OM_C.QUOTA_PLAN',
        }),
      })
    );
  }, []);

  const buttons: Buttons[] = [
    <Button
      icon="add"
      key="create"
      color={ButtonColor.default}
      funcType={FuncType.raised}
      onClick={() => handleCreate()}
      disabled={addFalg}
    >
      {intl.get(`dji.otc.om.view.button.create`).d('新建')}
    </Button>,
    <Button
      icon="delete"
      key="delete"
      color={ButtonColor.default}
      funcType={FuncType.raised}
      onClick={() => handleDelete()}
      disabled={addFalg}
    >
      {intl.get(`dji.otc.om.view.button.delete`).d('删除')}
    </Button>,
    <Button
      icon="get_app"
      key="import"
      color={ButtonColor.default}
      funcType={FuncType.raised}
      onClick={() => handleBatchExport()}
      disabled={addFalg}
    >
      {intl.get(`dji.otc.om.view.button.import`).d('导入')}
    </Button>,
  ];
  return (
    <Table
      style={{ margin: '20px 0' }}
      dataSet={tableDS}
      border
      queryFieldsLimit={3}
      columns={Columns}
      buttons={buttons}
      header={intl.get('dji.otc.om.view.title.distributionDetail').d('分货明细')}
    />
  );
};

export default connect()(ClassPage);
